package com.hoshiibuy.sys.permission.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiibuy.common.exception.CommonError;
import com.hoshiibuy.common.exception.ServiceException;
import com.hoshiibuy.common.rpc.Response;
import com.hoshiibuy.sys.permission.dao.SysModelsMapper;
import com.hoshiibuy.sys.permission.dao.SysPermissionesMapper;
import com.hoshiibuy.sys.permission.entity.SysModels;
import com.hoshiibuy.sys.permission.entity.SysPermissiones;
import com.hoshiibuy.sys.permission.feign.IdGeneratorRemote;
import com.hoshiibuy.sys.permission.service.ISysModelsService;

/**
 * <p>
 * 表述系统平台功能 服务实现类
 * </p>
 *
 * @author Mr.Wu
 * @since 2019-04-18
 */
@Service
public class SysModelsServiceImpl extends ServiceImpl<SysModelsMapper, SysModels> implements ISysModelsService {

	@Autowired
	private SysPermissionesMapper sysPermissionesMapper;

	@Autowired
	private SysModelsMapper sysModelsMapper;

	@Autowired
	private IdGeneratorRemote idGeneratorRemote;

	@Override
	public List<SysPermissiones> getPermissionesListById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysModel", "sysPermissiones" }, allEntries = true)
	public Response addSysModel(SysModels param) {
		int count = 0;
		String id = idGeneratorRemote.getId();
		param.setId(Long.valueOf(id));
		param.setAddTime(LocalDateTime.now());
		param.setUpdateTime(LocalDateTime.now());
		param.setVersion(1);

		// 接收权限数组
		List<String> permissionIdList = param.getPermissionIdList();
		if (permissionIdList != null && permissionIdList.size() > 0) {
			List<SysPermissiones> permissionesList = sysPermissionesMapper
					.selectList(new QueryWrapper<SysPermissiones>().in("id", param.getPermissionIdList()));

			// 权限所属系统修改为新增的系统
			for (SysPermissiones sysPermissiones : permissionesList) {
				sysPermissiones.setSystemId(param.getId());
				sysPermissiones.setUpdateTime(LocalDateTime.now());
				// TODO 获取修改人信息
				sysPermissiones.setModifiedby("admin");
				sysPermissiones.setVersion(sysPermissiones.getVersion() + 1);

				// 更新数据
				// TODO 改为批量更新
				count = sysPermissionesMapper.updateById(sysPermissiones);
				if (count <= 0) {
					throw new ServiceException(CommonError.error("修改权限关联失败"));
				}
			}
		}

		count = sysModelsMapper.insert(param);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("新增失败"));
		}
		return Response.success("新增成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysModel", "sysPermissiones" }, allEntries = true)
	public Response updateSysModel(SysModels param) {
		int count = 0;
		param.setUpdateTime(LocalDateTime.now());
		// TODO 获取修改人信息
		String modifyBy = "admin";
		count = sysModelsMapper.updateById(param);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("修改系统功能失败"));
		}
		List<String> permissionIdList = param.getPermissionIdList();
		if (permissionIdList != null && permissionIdList.size() > 0) {
			// 如果权限id列表不为空则把权限更新为列表内
			// 先移除再添加新的

			// 获取下属权限列表
			// 移除
			SysPermissiones queryParam = new SysPermissiones();
			queryParam.setSystemId(param.getId());
			QueryWrapper<SysPermissiones> queryWrapper = new QueryWrapper<SysPermissiones>(queryParam);
			List<SysPermissiones> permissionesList = sysPermissionesMapper.selectList(queryWrapper);
			for (SysPermissiones sysPermissiones : permissionesList) {
				sysPermissiones.setSystemId(null);
				sysPermissiones.setUpdateTime(LocalDateTime.now());
				sysPermissiones.setModifiedby(modifyBy);
				sysPermissiones.setVersion(sysPermissiones.getVersion() + 1);
				count = sysPermissionesMapper.updateById(sysPermissiones);
				if (count <= 0) {
					throw new ServiceException(CommonError.error("修改权限关联失败"));
				}
			}

			// 获取新列表
			// 添加
			permissionesList = sysPermissionesMapper.selectBatchIds(param.getPermissionIdList());

			// 权限所属系统修改为新增的系统
			for (SysPermissiones sysPermissiones : permissionesList) {
				sysPermissiones.setSystemId(param.getId());
				sysPermissiones.setUpdateTime(LocalDateTime.now());
				sysPermissiones.setModifiedby(modifyBy);
				sysPermissiones.setVersion(sysPermissiones.getVersion() + 1);
				count = sysPermissionesMapper.updateById(sysPermissiones);
				if (count <= 0) {
					throw new ServiceException(CommonError.error("修改权限关联失败"));
				}
			}
		}
		return Response.success("修改成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysModel", "sysPermissiones" }, allEntries = true)
	public Response deleteSysModel(String id) {
		int count = 0;
		count = sysModelsMapper.deleteById(id);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("删除失败"));
		}

		// 获取下属权限列表
		SysPermissiones queryParam = new SysPermissiones();
		queryParam.setSystemId(Long.valueOf(id));
		QueryWrapper<SysPermissiones> queryWrapper = new QueryWrapper<SysPermissiones>(queryParam);
		List<SysPermissiones> permissionesList = sysPermissionesMapper.selectList(queryWrapper);
		for (SysPermissiones sysPermissiones : permissionesList) {
			sysPermissiones.setSystemId(null);
			sysPermissiones.setUpdateTime(LocalDateTime.now());
			// TODO 获取修改人信息
			sysPermissiones.setModifiedby("admin");
			sysPermissiones.setVersion(sysPermissiones.getVersion() + 1);
			count = sysPermissionesMapper.updateById(sysPermissiones);
			if (count <= 0) {
				throw new ServiceException(CommonError.error("权限关联更新失败"));
			}
		}

		return Response.success("删除成功");
	}

	@Override
	@Cacheable(cacheNames = "sysModel", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5(Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	public Response getSysModelList(Wrapper<SysModels> queryWrapper) {
		return Response.data(sysModelsMapper.selectList(queryWrapper));
	}

	@Override
	@Cacheable(cacheNames = "sysModel", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
	public Response getSysModelDetail(String id) {
		SysModels model = sysModelsMapper.selectById(id);
		if (model != null) {
			// 获取权限ID列表
			SysPermissiones queryParam = new SysPermissiones();
			queryParam.setSystemId(Long.valueOf(id));
			QueryWrapper<SysPermissiones> queryWrapper = new QueryWrapper<SysPermissiones>(queryParam);
			List<SysPermissiones> list = sysPermissionesMapper.selectList(queryWrapper);
			model.setPermissionList(list);
			return Response.data(model);
		} else {
			return Response.failed("数据不存在");
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5('Page(current=' + #page.getCurrent() + ', size=' + #page.getSize() + '), Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	public Response getPage(IPage<SysModels> page, Wrapper<SysModels> queryWrapper) {
		return Response.data(sysModelsMapper.selectPage(page, queryWrapper));
	}

}
